How to create dictionary in python?Give suitable example.
How to create dictionary in python?
553
28-Mar-2023
Aryan Kumar
20-Apr-2023In Python, you can create a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. Each key-value pair consists of a key, followed by a colon :, and then the corresponding value.
Here's an example of creating a dictionary that maps names to ages:
You can also create an empty dictionary and add key-value pairs to it later using square bracket notation []:
You can also use the dict() constructor to create a dictionary from a list of tuples, where each tuple represents a key-value pair:
Once you have created a dictionary, you can access its values by using square bracket notation to specify the key:
Krishnapriya Rajeev
29-Mar-2023Dictionaries in Python are used to store data values in a key: value pair, unlike other data types that can hold only single values as an element. It is a collection that is ordered, and mutable and does not allow for duplicate values.
We can create a dictionary in Python as follows:
The values can be of any data type and can be duplicated, however, the keys cannot be duplicated and must be immutable. The keys are also case-sensitive.
We can add elements to a dictionary by using a new index key and assigning a value to it.
The update() method can be used to update the items within a dictionary. If the item does not exist, it will be added.